﻿from google.appengine.ext import db
from taggable import Taggable,Tag
#####没用了
class Gift(db.Model):
  name = db.StringProperty()

class GiftTransaction(db.Model):
  sender_id = db.StringProperty()
  receiver_id = db.StringProperty()
  gift = db.ReferenceProperty(Gift)

class Bug(db.Model):
  description = db.TextProperty()
  date_time = db.DateTimeProperty(auto_now=True)
#####没用了
class Category(db.Model,Taggable):
  cat = db.StringProperty(required=True)
  product_count = db.IntegerProperty(default=0)
  @classmethod
  def get_or_create(cls, cat_name):
      existing_cat = Category.get_by_key_name(unicode(cat_name))
      if existing_cat is None:
          # The tag does not yet exist, so create it.
          def create_cat_txn():
              new_cat = Category(key_name=unicode(cat_name), cat = unicode(cat_name))
              new_cat.put()
              return new_cat
          existing_cat = db.run_in_transaction(create_cat_txn)
      return existing_cat
  @classmethod
  def set_product_count(cls,cat_name,count):
    acat = cls.get_or_create(cat_name)
    acat.product_count = count
    acat.put()
    
    
class Product(db.Model,Taggable):
  category = db.CategoryProperty(default=u"其他")
  name = db.StringProperty()#required=True
  mod_num = db.StringProperty()
  pic_url = db.LinkProperty()
  big_pic_url = db.LinkProperty()
  direct_buy_url = db.LinkProperty()#required=True
  price = db.FloatProperty()
  point = db.FloatProperty()
  is_online = db.BooleanProperty( default=True)
  buy_count = db.IntegerProperty(default=0)
  rate_count = db.IntegerProperty(default=0)
  is_featured = db.BooleanProperty(default=False)
  added = db.DateTimeProperty(auto_now=True)
  modded = db.DateTimeProperty()
  def __init__(self, parent=None, key_name=None, app=None, **entity_values):
    db.Model.__init__(self, parent, key_name, app, **entity_values)
    Taggable.__init__(self)  
    self.__cat = None
  @classmethod
  def get_or_create(cls, buy_url):
      "Get the Product object that has the tag value given by tag_value."
      existing_product = Product.get_by_key_name(buy_url)
      if existing_product is None:
          # The tag does not yet exist, so create it.
          def create_product_txn():
              new_product = Product(key_name=buy_url)
              new_product.put()
              return new_product
          existing_product = db.run_in_transaction(create_product_txn)
      return existing_product
  @classmethod
  def get_products(cls, start_index=0, count=20):
      start_index = int(start_index) # Just make sure that we have an int
      products = Product.gql('WHERE is_online = TRUE LIMIT %d,%d'%(start_index,count)).fetch(count + 1)
      if len(products) > count:
          products = products[:count]
      return products
  @classmethod
  def get_featured_products(cls, start_index=0, count=20):
      start_index = int(start_index) # Just make sure that we have an int
      products = Product.gql('WHERE is_online = TRUE and featured = TRUE LIMIT %d,%d'%(start_index,count)).fetch(count + 1)
      if len(products) > count:
          products = products[:count]
      return products
      
  @classmethod
  def get_hot_products(cls, start_index=0, count=20):
      start_index = int(start_index) # Just make sure that we have an int
      products = Product.gql('WHERE is_online = TRUE ORDER BY buy_count DESC LIMIT %d,%d'%(start_index,count)).fetch(count + 1)
      if len(products) > count:
          products = products[:count]
      return products
      
  @classmethod
  def get_rated_products(cls, start_index=0, count=20):
      start_index = int(start_index) # Just make sure that we have an int
      products = Product.gql('WHERE is_online = TRUE ORDER BY rate_count DESC LIMIT %d,%d'%(start_index,count)).fetch(count + 1)
      if len(products) > count:
          products = products[:count]
      return products

  @classmethod
  def get_products_by_tags(cls, tags ,start_index=0, count=20):
      import types
      products = None
      start_index = int(start_index) # Just make sure that we have an int
      count = int(count)
      if type(tags) is types.UnicodeType:
        # Convert unicode to a plain string
        tags = str(tags.encode('UTF-8'))
      if type(tags) is types.StringType:
        # Tags is a string, split it on tag_seperator into a list
        tags = string.split(tags, self.tag_separator)
      if type(tags) is types.ListType:
        keys=None
        for each_tag in tags:
          if keys is None:
            keys = each_tag.taged
          else:
            keys = filter(lambda x:x in each_tag.taged,keys)
      if len(keys) > start_index+count  :
        products = Product.get(keys[start_index:count])
        return products
      elif  len(keys) > 0:
        products = Product.get(keys)
        return products
      return []

      
  def delete(self):

    self.set_tags([])
    
    # Finally, call the real delete
    db.Model.delete(self)
  # def __get_cat(self):
    # if self.__cat is None:
      # return ''
    
    # return self.__cat.tag
  # def __set_cat(self,cat):
    # self.tags = cat
    # __cat = Tag.get_or_create(cat.encode('UTF-8'))
    # __cat.is_category = True
    # __cat.put()
  
  #category = property(__get_cat, __set_cat, None, None)
#  @classmethod
#  def get_tag(cls):
#    return Tag.get_tags_by_name()
  
  
class Member(db.Model):
  container = db.StringProperty(required=True)
  masterid = db.StringProperty()
  mastername = db.StringProperty()
  user_id = db.StringProperty(required=True)
  photo_url = db.StringProperty()
  slavenum = db.IntegerProperty(default=0)
  name = db.StringProperty(required=True)
  ship_addr = db.PostalAddressProperty()
  phone = db.PhoneNumberProperty()
  email = db.EmailProperty()
  im = db.IMProperty()
  pay_account = db.EmailProperty()
  is_active = db.BooleanProperty()
  cash = db.FloatProperty()
  point = db.FloatProperty()
  tax_rate = db.FloatProperty()
  def setMaster(self,player):
    self.masterid = player.userId
    self.mastername = player.name
  
class LuckyNum(db.Model):
  date = db.DateProperty()
  sn = db.IntegerProperty()#期数
  open_date = db.DateProperty()
  num = db.IntegerProperty()
  
class DrawMoneyTransaction(db.Model):
  customer_id = db.ReferenceProperty(Member)
  lucky_num = db.IntegerProperty()
  bid_date = db.DateProperty()
  sn = db.IntegerProperty()
  bid_point = db.FloatProperty()
  money = db.FloatProperty()
  transaction_phase = db.StringProperty(choices=('bid','pay'))
  
class BuyProductTransaction(db.Model):
  customer = db.ReferenceProperty(Member)
  product = db.ReferenceProperty(Product)
  count = db.IntegerProperty()
  shipping_fee = db.FloatProperty()
  total_price = db.FloatProperty()
  total_point = db.FloatProperty()
  bid_date = db.DateProperty()
  transaction_phase = db.StringProperty(choices=('bid','mod_price','pay','shipping','confirm'))

